package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.cmpe.group6.storyroad.ListAdapters.RecommendationAdapter;
import com.cmpe.group6.storyroad.jsonClasses.RecommendationHolder;
import com.cmpe.group6.storyroad.jsonClasses.StoryView;
import com.google.gson.Gson;

/** Activity that shows recommended stories for the current user.
 *
 */
public class RecommendationsActivity extends Activity {

	private ListView recommendationList;
	private StoryView[] recommendations;
	private ProgressBar progressBar;
	private Context currentContext;
	private final List<String> story_titles = new ArrayList<String>();
	private final List<String> story_ratings = new ArrayList<String>();
	private final List<String> story_ids = new ArrayList<String>();
	private final List<String> story_tags = new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recommendations);

		currentContext = this;

		final ActionBar bar = getActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		bar.setDisplayShowTitleEnabled(false);

		recommendationList = (ListView) findViewById(R.id.recommendationList);
		progressBar = (ProgressBar) findViewById(R.id.progressBar_recom);

		RecommendationTask rTask = new RecommendationTask();
		rTask.execute((Void) null);

		// Clicking on an item will direct the user to that story's page.
		recommendationList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						String storyId = (String) recommendationList
								.getItemAtPosition(position);
						Intent readStoryIntent = new Intent(
								getApplicationContext(),
								ReadStoryActivity.class);
						readStoryIntent.putExtra("story_id", storyId);
						startActivity(readStoryIntent);
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	// Activating the top bar.
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home_button:
			Intent mainIntent = new Intent(this, MainActivity.class);
			startActivity(mainIntent);
			return true;
		case R.id.recommendations_button:
			return true;
		case R.id.profile_button:
			Intent profileIntent = new Intent(this, ProfileActivity.class);
			startActivity(profileIntent);
			return true;
		case R.id.search_button:
			Intent searchIntent = new Intent(this, SearchActivity.class);
			startActivity(searchIntent);
			return true;
		case R.id.following_button:
			Intent followIntent = new Intent(this, FollowingActivity.class);
			startActivity(followIntent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Represents an asynchronous Recommendation task for getting the
	 * recommended stories for the user from the server.
	 * 
	 */
	public class RecommendationTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME
					+ "GetRecommendations");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						3);
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				recommendations = gson.fromJson(jsonResponse,
						RecommendationHolder.class).recommendations;

				for (StoryView sView : recommendations) {
					story_titles.add(sView.getTitle());
					story_ratings.add(String.valueOf(sView.getAvgRating()));
					story_ids.add(String.valueOf(sView.getS_id()));
					story_tags.add(String.valueOf(sView.getTags()));
				}

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return true;
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(getApplicationContext(), "Connection Error",
						Toast.LENGTH_SHORT).show();
			}
			RecommendationAdapter adapter = new RecommendationAdapter(
					currentContext, story_titles, story_ratings, story_ids,
					story_tags);
			recommendationList.setAdapter(adapter);
			progressBar.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {

		}
	}

}
